package socket

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"strings"
)

// Define our message object
type Message struct {
	From    string `json:"from"`
	To string `json:"to"`
	Message  interface{} `json:"message"`
}

var clients = make(map[string]*websocket.Conn) // connected clients
var messages = make(chan Message)           // messages channel

// Configure the upgrader
var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

//webSocket
func Ws(c *gin.Context) {
	uuid := c.Param("uuid")
	if strings.Trim(uuid, " ") == "" {
		c.JSONP(501,gin.H{"status": "not found uuid"})
		return
	}
	//升级get请求为webSocket协议
	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer ws.Close()
	// Register our new client
	clients[uuid] = ws
	for {
		var msg Message
		// Read in a new message as JSON and map it to a Message object
		err := ws.ReadJSON(&msg)
		if err != nil {
			log.Printf("error: %v", err)
			delete(clients, uuid)
			break
		}
		// Send the newly received message to the messages channel
		messages <- msg
	}
}

func init()  {
	go wsHandleMessages()
}
//处理消息队列
func wsHandleMessages() {
	for {
		// Grab the next message from the messages channel
		msg := <-messages
		// Send it out to every client that is currently connected
		client, ok := clients[msg.To]
		if !ok {
			continue
		}
		err := client.WriteJSON(msg)
		if err != nil {
			log.Printf("error: %v", err)
			client.Close()
			delete(clients, msg.To)
		}
	}
}
